#!/bin/bash

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

default_local_path="."
default_remote_path="~/project"
default_ssh_host="northwest1.gpugeek.com"
default_ssh_port="56740"
default_ssh_user="root"

parse_env() {
    if [ -f ".env" ] && [ -z "$ssh_host" ] && [ -z "$ssh_port" ] && [ -z "$ssh_user" ]; then
        ssh_connection=$(grep "^SSH_CONNECTION=" .env | cut -d'=' -f2- | sed "s/^['\"]//;s/['\"]$//" | xargs)
        if [ -n "$ssh_connection" ]; then
            if echo "$ssh_connection" | grep -qE '\-p\s+[0-9]+'; then
                ssh_port=$(echo "$ssh_connection" | grep -oE '\-p\s+[0-9]+' | awk '{print $2}')
            fi
            if echo "$ssh_connection" | grep -qE '[a-zA-Z0-9_\-]+@[a-zA-Z0-9._\-]+'; then
                ssh_user_host=$(echo "$ssh_connection" | grep -oE '[a-zA-Z0-9_\-]+@[a-zA-Z0-9._\-]+')
                ssh_user=$(echo "$ssh_user_host" | cut -d'@' -f1)
                ssh_host=$(echo "$ssh_user_host" | cut -d'@' -f2)
            fi
            if grep -q "^REMOTE_PATH=" .env; then
                remote_path=$(grep "^REMOTE_PATH=" .env | cut -d'=' -f2- | sed "s/^['\"]//;s/['\"]$//" | xargs)
            fi
        fi
    fi
}

print_info() {
    echo -e "${YELLOW}=== Rsync 上传脚本 ===${NC}"
    echo -e "本地路径: ${GREEN}${local_path}${NC}"
    echo -e "远程路径: ${GREEN}${remote_path}${NC}"
    echo -e "SSH连接: ${GREEN}${ssh_user}@${ssh_host}:${ssh_port}${NC}"
}

check_ssh_connection() {
    echo -e "${YELLOW}测试SSH连接...${NC}"
    if ! ssh -p $ssh_port -o ConnectTimeout=10 $ssh_user@$ssh_host "echo 'SSH连接成功'" 2>/dev/null; then
        echo -e "${RED}❌ SSH连接失败！请检查主机、端口、用户名是否正确${NC}"
        exit 1
    fi
    echo -e "${GREEN}✅ SSH连接测试成功${NC}"
}

do_rsync() {
    if [ "$local_path" = "." ]; then
        echo -e "${YELLOW}使用gitignore模式（排除数据文件）${NC}"
        rsync -avz --progress --delete \
            --exclude-from=.gitignore \
            -e "ssh -p $ssh_port" \
            "$local_path/" "$ssh_user@$ssh_host:$remote_path/"
    else
        echo -e "${YELLOW}使用全量上传模式（包含所有文件）${NC}"
        rsync -avz --progress --delete \
            --exclude='.git/' \
            --exclude='.DS_Store' \
            --exclude='Thumbs.db' \
            -e "ssh -p $ssh_port" \
            "$local_path/" "$ssh_user@$ssh_host:$remote_path/"
    fi
}

main() {
    local_path="${1:-$default_local_path}"
    remote_path="${2:-$default_remote_path}"
    ssh_host="${3:-}"
    ssh_port="${4:-}"
    ssh_user="${5:-}"

    parse_env

    ssh_host="${ssh_host:-$default_ssh_host}"
    ssh_port="${ssh_port:-$default_ssh_port}"
    ssh_user="${ssh_user:-$default_ssh_user}"
    remote_path="${remote_path:-$default_remote_path}"

    print_info
    check_ssh_connection
    do_rsync

    echo -e "${GREEN}✅ 上传完成！${NC}"
    echo -e "${YELLOW}连接服务器: ssh -p $ssh_port $ssh_user@$ssh_host${NC}"
}

main "$@"
